package com.edz.from0507to0513apk.View;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.edz.from0507to0513apk.Base.BaseActivity;
import com.edz.from0507to0513apk.R;
import com.edz.from0507to0513apk.Service.TestService;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

public class SocketTestActivity extends BaseActivity {

    @BindView(R.id.btn_send_ontime)
    Button btn_send_ontime;

    private Handler mMainHandler;           // 用于将从服务器获取的消息显示出来
    private Socket socket;
    private ExecutorService mThreadPool;    // 线程池

    InputStream is;                         // 输入流对象
    OutputStream outputStream;              // 输出流对象
    //    BufferedReader br;
    String response;                        // 接收服务器发送过来的消息

    private Button btnConnect, btnDisconnect, btnSend;
    private TextView Receive, receive_message;
    private EditText mEdit;
    private static final String TAG = "SocketTestActivity";

    @Override
    protected void initView() {
        btnConnect = (Button) findViewById(R.id.connect);
        btnDisconnect = (Button) findViewById(R.id.disconnect);
        btnSend = (Button) findViewById(R.id.send);
        mEdit = (EditText) findViewById(R.id.edit);
        receive_message = (TextView) findViewById(R.id.receive_message);
        Receive = (Button) findViewById(R.id.Receive);
    }

    @Override
    protected void initData() {
        // 初始化线程池
        mThreadPool = Executors.newCachedThreadPool();

        mMainHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        receive_message.setText(response);
                        break;
                }
            }
        };
    }

    @Override
    protected void setEvent() {
        btnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 利用线程池直接开启一个线程 & 执行该线程
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // 创建Socket对象 & 指定服务端的IP 及 端口号
                            socket = new Socket("192.168.0.34", 8899);
                            // 判断客户端和服务器是否连接成功
                            System.out.println("当前连接状态===" + socket.isConnected());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });

        /**
         * 接收 服务器消息
         */
        Receive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 利用线程池直接开启一个线程 & 执行该线程
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (socket == null)
                                socket = new Socket("192.168.0.34", 8899);
                            // 步骤1：创建输入流对象InputStream
                            is = socket.getInputStream();
                            // 步骤2：创建输入流读取器对象 并传入输入流对象
                            // 该对象作用：获取服务器返回的数据
                            InputStream inputStream = socket.getInputStream();
                            DataInputStream input = new DataInputStream(inputStream);

                            // 步骤3：通过输入流读取器对象 接收服务器发送过来的数据
                            byte[] b = new byte[10000];
                            int length = input.read(b);
                            response = new String(b, 0, length, "utf-8");
                            Log.i("data", response);

                            // 步骤4:通知主线程,将接收的消息显示到界面
                            Message message = new Message();
                            message.what = 0;
                            message.obj = response;
                            mMainHandler.sendMessage(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });

            }
        });


        /**
         * 发送消息 给 服务器
         */
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 利用线程池直接开启一个线程 & 执行该线程
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // 步骤1：从Socket 获得输出流对象OutputStream
                            // 该对象作用：发送数据
                            if (socket == null)
                                socket = new Socket("192.168.0.33", 8899);
                            Log.i("lian jie statu", socket.isConnected() + "");
                            outputStream = socket.getOutputStream();
                            // 步骤2：写入需要发送的数据到输出流对象中
                            outputStream.write((mEdit.getText().toString() + "\n").getBytes("utf-8"));
                            // 特别注意：数据的结尾加上换行符才可让服务器端的readline()停止阻塞
                            // 步骤3：发送数据到服务端
                            outputStream.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
        });


        /**
         * 断开客户端 & 服务器的连接
         */
        btnDisconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    // 断开 客户端发送到服务器 的连接，即关闭输出流对象OutputStream
                    if (socket != null && outputStream != null) {
                        outputStream.close();
                        // 断开 服务器发送到客户端 的连接，即关闭输入流读取器对象BufferedReader
//                        br.close();
                        // 最终关闭整个Socket连接
                        socket.close();
                        // 判断客户端和服务器是否已经断开连接
                        System.out.println("当前连接状态===" + socket.isConnected());
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        btn_send_ontime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startOntimeTask();
            }
        });

//        btn_send_ontime.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent service = new Intent(SocketTestActivity.this,TestService.class);
//                startService(service);
//                Log.i(TAG,"start service");
//            }
//        });
    }

    //开启定时
    private void startOntimeTask() {
        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
        service.scheduleAtFixedRate(runnable, 5, 20, TimeUnit.SECONDS);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(socket == null){
                try {
                    Socket socket = new Socket("192.168.0.34", 8899);
                    outputStream = socket.getOutputStream();
                    // 步骤2：写入需要发送的数据到输出流对象中
                    outputStream.write(("data on time activity" + "\n").getBytes("utf-8"));
                    // 特别注意：数据的结尾加上换行符才可让服务器端的readline()停止阻塞
                    // 步骤3：发送数据到服务端
                    outputStream.flush();
                }catch (Exception e){
                    e.getMessage();
                }
            }
        }
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_socket_test;
    }
}
